package com.baidu.mpks.user.service;


import com.baidu.mpks.common.RedisClient;
import com.baidu.mpks.exception.BusinessException;
import com.baidu.mpks.permission.service.PermissionCacheService;
import com.baidu.mpks.role.domain.Role;
import com.baidu.mpks.role.service.RoleService;
import com.baidu.mpks.user.dao.UserDao;
import com.baidu.mpks.user.dao.UserFirstLoginDao;
import com.baidu.mpks.user.domain.ShenFeiOrgDTO;
import com.baidu.mpks.user.domain.ShenFeiUserDTO;
import com.baidu.mpks.user.domain.User;
import com.baidu.mpks.user.domain.UserSync;
import com.baidu.mpks.user.dto.UserResourcesResponse;
import com.baidu.mpks.user.vo.UserExport;
import com.baidu.mpks.user.vo.UserParam;
import com.baidu.mpks.usergroup.dao.UserGroupDao;
import com.baidu.mpks.usergroup.domain.UserGroup;
import com.baidu.mpks.usergroup.dto.Resources;
import com.baidu.mpks.usergroup.enums.ResourceType;
import com.baidu.mpks.usergroup.enums.UserGroupType;
import com.baidu.mpks.usergroup.service.UserGroupService;
import com.baidu.mpks.util.MysqlUtil;
import com.baidu.mpks.util.Sm3Utils;
import com.baidu.mpks.utils.CommonUtils;
import com.baidu.mpks.utils.SecurityUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    UserDao userDao;
    @Autowired
    UserGroupDao userGroupDao;
    @Autowired
    UserFirstLoginDao userFirstLoginDao;
    @Autowired
    RoleService roleService;
    @Autowired
    private SecurityUtil securityUtil;
    @Autowired
    @Lazy
    UserGroupService userGroupService;
    @Autowired
    RedisClient redisClient;
    @Autowired
    PermissionCacheService permissionCacheService;
    @Value("${shenfei.admin.account}")
    String adminAccount;
    private static String userTagPrefix = "user:tag:";
    private static final String SPLIT_COMMA = ",";

    public UserServiceImpl() {
    }

    public User login(String account, String password, boolean rememberMe) throws Exception {
        User user = this.userDao.findByAccount(account);
        if (user == null) {
            return null;
        } else {
            user.setPassword(password);
            password = this.createPassword(user);
            UsernamePasswordToken token = new UsernamePasswordToken(account, password);
            token.setRememberMe(rememberMe);
            SecurityUtils.getSubject().login(token);
            return user;
        }
    }

    public User findByAccount(String account) {
        return this.userDao.findByAccount(account);
    }

    public List<User> findUserListByRoleId(String roleId, String status, String userName, String trueName, Integer pageNum, Integer pageSize) {
        List<User> users = this.userDao.findUserList(roleId, status, userName, trueName, (Integer)null, (Date)null, (Date)null, (pageNum - 1) * pageSize, pageSize);
        return users;
    }

    public Map<String, Object> getUserRoleList(String roleId, String status, String userName, String trueName, Integer deptId, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        List<UserParam> userParamList = new ArrayList();
        Map<String, Object> result = new HashMap();
        Date st = null;
        Date et = null;
        this.getUserParamList(roleId, status, userName, trueName, deptId, pageNum, pageSize, userParamList, (Date)st, (Date)et, startTime, endTime);
        Integer total = this.userDao.findUserListCount(roleId, status, MysqlUtil.replaceLikeString(userName), MysqlUtil.replaceLikeString(trueName), deptId, (Date)st, (Date)et);
        result.put("list", userParamList);
        result.put("totalSize", total);
        return result;
    }

    private void getUserParamList(String roleId, String status, String userName, String trueName, Integer deptId, Integer pageNum, Integer pageSize, List<UserParam> userParamList, Date st, Date et, String startTime, String endTime) {
        List<String> adminAccounts = new ArrayList();
        if (StringUtils.isNotEmpty(this.adminAccount)) {
            String[] accounts = this.adminAccount.split(",");
            CollectionUtils.addAll(adminAccounts, accounts);
        }

        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            st = new Date(Long.parseLong(startTime));
            et = new Date(Long.parseLong(endTime));
        }

        List<User> userList = this.userDao.findUserList(roleId, status, MysqlUtil.replaceLikeString(userName), MysqlUtil.replaceLikeString(trueName), deptId, st, et, (pageNum - 1) * pageSize, pageSize);
        new ArrayList();
        Iterator var16 = userList.iterator();

        while(var16.hasNext()) {
            User user = (User)var16.next();
            if (!adminAccounts.contains(user.getUserName())) {
                UserParam userParam = new UserParam();
                BeanUtils.copyProperties(user, userParam);
                List<Resources> roleList = this.getUserAllRoles(user.getUserId());
                String roleIds = (String)roleList.stream().map((item) -> {
                    return item.getId().toString();
                }).collect(Collectors.joining(","));
                userParam.setRoleIds(roleIds);
                userParam = this.setDeptByUserId(userParam);
                userParamList.add(userParam);
            }
        }

    }

    @Transactional
    public void updateUser(UserParam userParam, String roleIds) {
        User user = new User();
        BeanUtils.copyProperties(userParam, user);
        if (StringUtils.isNotEmpty(roleIds)) {
            List<Integer> roleIdList = new ArrayList();
            String[] roleIdsArr = roleIds.split(",");

            for(int i = 0; i < roleIdsArr.length; ++i) {
                if (!roleIdsArr[i].equals("")) {
                    roleIdList.add(Integer.parseInt(roleIdsArr[i]));
                }
            }

            if (roleIdList.size() != 0) {
                this.userDao.deleteUserOrRole(user.getUserId());
                this.insertUserOrRole(user.getUserId(), roleIdList);
            }
        }

        this.userDao.update(user);
        if (userParam.getDeptId() != null) {
            UserGroup userGroup = this.userGroupService.checkAndGetUserGroup(userParam.getDeptId());
            this.userGroupService.removeUsersByType(UserGroupType.DEPARTMENT.getName(), Lists.newArrayList(new String[]{user.getUserId()}));
            this.userGroupService.addUsers(userGroup.getId(), Lists.newArrayList(new UserParam[]{userParam}));
        }

    }

    @Transactional
    public void updateUserByUserId(User user, String roleIds) {
        List<Integer> roleIdList = new ArrayList();
        String[] roleIdsArr = roleIds.split(",");

        for(int i = 0; i < roleIdsArr.length; ++i) {
            if (!roleIdsArr[i].equals("")) {
                roleIdList.add(Integer.parseInt(roleIdsArr[i]));
            }
        }

        this.userDao.updateByUserId(user);
        if (roleIdList.size() != 0) {
            this.userDao.deleteUserOrRole(user.getUserId());
            this.insertUserOrRole(user.getUserId(), roleIdList);
        }

    }

    @Transactional
    public void updateUserStatus(User user) {
        this.userDao.updateUserStatus(user);
    }

    @Transactional
    public void deleteUser(User user) {
        this.userDao.delete(user);
        this.userDao.deleteUserOrRole(user.getUserId());
        this.deleteUserFirstLogin(user.getUserId());
        this.userGroupService.removeUserByUserId(user.getUserId());
    }

    public User findByUserId(String userId) {
        return this.userDao.findByUserId(userId);
    }

    public Map<String, User> findByUserIds(List<String> userIds) {
        Map<String, User> map = new HashMap();
        if (CollectionUtils.isEmpty(userIds)) {
            return map;
        } else {
            List<User> users = this.userDao.findByUserIds(userIds);
            Iterator var4 = users.iterator();

            while(var4.hasNext()) {
                User user = (User)var4.next();
                map.put(user.getUserId(), user);
            }

            return map;
        }
    }

    private String createPassword(User user) {
        String password = Sm3Utils.encrypt(user.getPassword());
        return password;
    }

    @Transactional
    public void updatePwdAndName(User user) {
        String password = this.createPassword(user);
        user.setPassword(password);
        user.setIsActive(1);
        this.userDao.updateUserNameAndPassword(user);
    }

    @Transactional
    public void updatePwd(User user) {
        String password = this.createPassword(user);
        user.setPassword(password);
        this.userDao.updatePassword(user);
    }

    @Transactional
    public void updateUserRoles(List<String> userIds, List<Integer> roleIds) {
        Iterator var3 = userIds.iterator();

        while(var3.hasNext()) {
            String userId = (String)var3.next();
            this.userDao.deleteUserOrRole(userId);
            this.insertUserOrRole(userId, roleIds);
        }

        this.permissionCacheService.clearPermissionAll();
    }

    @Transactional
    public User addUser(User user, String roleIds) {
        UUID uuid = UUID.randomUUID();
        String userId = uuid.toString().replaceAll("-", "");
        user.setUserId(userId);
        user.setRoleIds(roleIds);
        this.addUserAtom(user);
        return user;
    }

    @Transactional
    public void addUserAtom(User user) {
        List<Integer> roleIdList = new ArrayList();
        if (StringUtils.isNotEmpty(user.getRoleIds())) {
            String[] roleIdsArr = user.getRoleIds().split(",");

            for(int i = 0; i < roleIdsArr.length; ++i) {
                roleIdList.add(Integer.parseInt(roleIdsArr[i]));
            }
        }

        user.setUserId(user.getUserId());
        user.setCode(this.makeCode());
        if (ObjectUtils.isEmpty(user.getIsActive())) {
            user.setIsActive(0);
        }

        this.userDao.insert(user);
        this.insertUserOrRole(user.getUserId(), roleIdList);
    }

    private String makeCode() {
        String code = "";
        UUID uuid = UUID.randomUUID();
        code = uuid.toString().replaceAll("-", "");
        return code;
    }

    @Transactional
    public User initUser(User user) {
        user.setCode(this.makeCode());
        this.userDao.initUser(user);
        return this.userDao.findByUserId(user.getUserId());
    }

    @Transactional
    public User syncUser(UserSync userSync) {
        User user = new User(this.securityUtil.getUserIdOrDefault(""));
        BeanUtils.copyProperties(userSync, user);
        User sysUser;
        if (userSync.getOpType().equals("add")) {
            sysUser = this.userDao.findByAccount(user.getUserName());
            if (sysUser != null) {
                throw new BusinessException(user.getUserName() + "用户名已存在");
            }

            this.addUserAtom(user);
        } else if (userSync.getOpType().equals("del")) {
            Date now = new Date();
            user.setDeleteTime(now);
            this.deleteUser(user);
        } else if (userSync.getOpType().equals("mod")) {
            sysUser = this.userDao.findByAccount(user.getUserName());
            if (sysUser != null && !sysUser.getUserId().equals(user.getUserId())) {
                throw new BusinessException(user.getUserName() + "用户名已存在，请更换用户名内容");
            }

            this.updateUserByUserId(user, user.getRoleIds());
        }

        return user;
    }

    public Map<String, Object> getDeptByUserId(String userId) {
        Map<String, Object> deptMap = new HashMap();
        List<UserGroup> userGroups = this.userGroupService.getUserGroupsByUserId(userId, UserGroupType.DEPARTMENT.getName());
        if (CollectionUtils.isNotEmpty(userGroups)) {
            deptMap.put("deptId", ((UserGroup)userGroups.get(0)).getId());
            deptMap.put("deptName", ((UserGroup)userGroups.get(0)).getName());
        }

        return deptMap;
    }

    public List<User> getNoDeptUsers() {
        return this.userDao.findNoDeptUsers();
    }

    public UserParam getUserInfo(String userId) throws InvocationTargetException, IllegalAccessException {
        User user = this.userDao.findByUserId(userId);
        if (user == null) {
            return null;
        } else {
            UserParam userParam = new UserParam();
            org.apache.commons.beanutils.BeanUtils.copyProperties(userParam, user);
            Map<Integer, Resources> userInheritRolesMap = this.getUserInheritRoles(userId);
            List<Role> roleList = this.roleService.findByUserId(userParam.getUserId());
            roleList.removeIf((e) -> {
                return userInheritRolesMap.containsKey(e.getId());
            });
            if (roleList.size() > 0) {
                String roleIds = (String)roleList.stream().map((item) -> {
                    return item.getId().toString();
                }).collect(Collectors.joining(","));
                userParam.setRoleIds(roleIds);
            }

            List<Resources> userInheritRoles = (List)userInheritRolesMap.values().stream().collect(Collectors.toList());
            userParam.setUserInheritRoles(userInheritRoles);
            userParam = this.setDeptByUserId(userParam);
            return userParam;
        }
    }

    public Map<Integer, Resources> getUserInheritRoles(String userId) {
        List<Resources> userInheritRoles = new ArrayList();
        List<UserGroup> groups = this.userGroupService.getUserGroupsByUserId(userId, UserGroupType.DEPARTMENT.getName());
        Set<UserGroup> groupSet = new HashSet();
        if (groups != null) {
            groups.forEach((e) -> {
                this.userGroupService.recurGroup(e.getId(), groupSet);
            });
        }

        Set<Integer> groupIdSet = new HashSet();
        groupSet.forEach((e) -> {
            groupIdSet.add(e.getId());
        });
        Iterator var6 = groupIdSet.iterator();

        while(var6.hasNext()) {
            Integer groupId = (Integer)var6.next();
            List<Resources> tempList = this.userGroupService.getRolesByGroup(groupId);
            if (tempList != null) {
                userInheritRoles.addAll(tempList);
            }
        }

        Map<Integer, Resources> userInheritRolesMap = (Map)userInheritRoles.stream().collect(Collectors.toMap(Resources::getId, Function.identity(), (key1, key2) -> {
            return key2;
        }));
        return userInheritRolesMap;
    }

    public List<Resources> getUserAllRoles(String userId) {
        List<Role> roleList = this.roleService.findByUserId(userId);
        Map<Integer, Resources> userInheritRolesMap = this.getUserInheritRoles(userId);
        roleList.removeIf((e) -> {
            return userInheritRolesMap.containsKey(e.getId());
        });
        List<Resources> allRoles = (List)roleList.stream().map((temp) -> {
            Resources resources = new Resources();
            resources.setName(temp.getRoleName());
            resources.setId(temp.getId());
            return resources;
        }).collect(Collectors.toList());
        allRoles.addAll((Collection)userInheritRolesMap.values().stream().collect(Collectors.toList()));
        return allRoles;
    }

    public List<Integer> getUserAllRoleIds(String userId) {
        return (List)this.getUserAllRoles(userId).stream().map(Resources::getId).collect(Collectors.toList());
    }

    public void deleteResourcesByUserId(String userId, String type) {
        this.userDao.deleteResourcesByUserId(userId, type);
    }

    private UserParam setDeptByUserId(UserParam userParam) {
        Map<String, Object> deptMap = this.getDeptByUserId(userParam.getUserId());
        if (MapUtils.isNotEmpty(deptMap)) {
            userParam.setDeptName(deptMap.get("deptName").toString());
            userParam.setDeptId(Integer.valueOf(deptMap.get("deptId").toString()));
        }

        return userParam;
    }

    public List<Map<String, Object>> getDeptByUserIds(List<String> userIds) {
        List<Map<String, Object>> result = new ArrayList();
        Set<UserGroup> userGroups = this.userGroupService.getUserGroupsByUserIds(userIds, UserGroupType.DEPARTMENT.getName());
        if (CollectionUtils.isNotEmpty(userGroups)) {
            Iterator var4 = userGroups.iterator();

            while(var4.hasNext()) {
                UserGroup userGroup = (UserGroup)var4.next();
                Map<String, Object> deptMap = new HashMap();
                deptMap.put("deptId", userGroup.getId());
                deptMap.put("deptName", userGroup.getName());
                result.add(deptMap);
            }
        }

        return result;
    }

    public List<Resources> getResourcesByUserId(String userId, String type) {
        List<Resources> resourcesList = this.userDao.findResourcesByUserId(userId, type);
        return resourcesList;
    }

    public UserResourcesResponse getAllResourcesByUserId(String userId, String type) {
        List<Resources> userResourceList = this.getResourcesByUserId(userId, type);
        List<UserGroup> userGroupList = this.userGroupService.getUserGroupsByUserId(userId, UserGroupType.DEPARTMENT.getName());
        Map<String, Resources> groupTagMap = new HashMap();
        if (userGroupList != null) {
            userGroupList.forEach((userGroup) -> {
                List<Resources> groupTagList = this.userGroupService.getResourcesByGroup(userGroup.getId(), ResourceType.TAG.getName());
                Map<String, Resources> tempMap = (Map)groupTagList.stream().collect(Collectors.toMap(Resources::getName, Function.identity(), (tag1, tag2) -> {
                    return tag1;
                }));
                groupTagMap.putAll(tempMap);
            });
        }

        userResourceList.removeIf((e) -> {
            return groupTagMap.containsKey(e.getName());
        });
        List<Resources> userGroupResourceList = new ArrayList(groupTagMap.values());
        UserResourcesResponse resp = new UserResourcesResponse(userResourceList, userGroupResourceList, (List)null);
        return resp;
    }

    public void addResources(String userId, String type, List<Resources> resourcesList) {
        if (!StringUtils.isEmpty(userId) && !CollectionUtils.isEmpty(resourcesList)) {
            if (ResourceType.TAG.getName().equals(type)) {
                List<Resources> userTags = this.getResourcesByUserId(userId, type);
                if (CollectionUtils.isNotEmpty(userTags)) {
                    resourcesList.addAll(userTags);
                }

                Map<String, Resources> map = (Map)resourcesList.stream().collect(Collectors.toMap(Resources::getName, Function.identity(), (tag1, tag2) -> {
                    return tag1;
                }));
                this.userDao.insertResourcesByUserId(userId, type, (List)map.values().stream().collect(Collectors.toList()));
            }

        }
    }

    public void deleteResourcesById(String userId, String type, List<Integer> resourcesIds) {
        if (userId != null) {
            this.userDao.deleteResourcesByUserIdAndResourceId(userId, type, resourcesIds);
        }

    }

    public void deleteResourcesByName(String userId, String type, List<String> resourcesNames) {
        if (userId != null) {
            this.userDao.deleteResourcesByUserIdAndResourceName(userId, type, resourcesNames);
        }

    }

    public Integer findUserFirstLogin(String userId, String menu) {
        return this.userFirstLoginDao.findUserFirstLogin(userId, menu) == null ? 1 : 0;
    }

    public void insertUserFirstLogin(String userId, String menu) {
        this.userFirstLoginDao.insertUserFirstLogin(userId, menu);
    }

    public void deleteUserFirstLogin(String userId) {
        this.userFirstLoginDao.deleteUserFirstLogin(userId);
    }

    public void deleteUserFirstLogin(String userId, String menu) {
        this.userFirstLoginDao.deleteUserFirstLoginByMenu(userId, menu);
    }

    public int insertUserOrRole(String userId, List<Integer> roleIds) {
        return CollectionUtils.isNotEmpty(roleIds) ? this.userDao.insertUserOrRole(userId, roleIds) : 0;
    }

    public List<String> getOrderedTags(String userId) {
        List<String> orderedTagList = new ArrayList();
        String tagStr = this.userDao.getOrderedTagsByUserId(userId);
        if (StringUtils.isNotEmpty(tagStr)) {
            orderedTagList = (List)Arrays.stream(tagStr.split(",")).collect(Collectors.toList());
        }

        return (List)orderedTagList;
    }

    public void updateOrderedTags(String userId, List<String> tags) {
        if (CollectionUtils.isNotEmpty(tags)) {
            this.userDao.updateOrderedTags(userId, StringUtils.join(tags, ","));
        }

    }

    public void deleteOrderedTags(String userId) {
        if (StringUtils.isNotEmpty(userId)) {
            this.userDao.deleteOrderedTagsByUserId(userId);
        }

    }

    public void addOrderedTags(String userId, List<String> tags) {
        if (CollectionUtils.isNotEmpty(tags) && StringUtils.isNotEmpty(userId)) {
            this.userDao.insertOrderedTags(userId, StringUtils.join(tags, ","));
        }

    }

    public void deduplicationTags(@NotNull List<String> orderedTags, @NotNull List<String> departmentTags, @NotNull List<String> userTags) {
        Set<String> allTagSet = new HashSet();
        Set<String> orderedTagSet = new HashSet();
        allTagSet.addAll(departmentTags);
        allTagSet.addAll(userTags);
        orderedTags.removeIf((e) -> {
            return !allTagSet.contains(e);
        });
        orderedTagSet.addAll(orderedTags);
        orderedTags.addAll((Collection)departmentTags.stream().filter((e) -> {
            return !orderedTagSet.contains(e);
        }).collect(Collectors.toList()));
        orderedTags.addAll((Collection)userTags.stream().filter((e) -> {
            return !orderedTagSet.contains(e);
        }).collect(Collectors.toList()));
    }

    @Transactional
    public void synShenFeiInfo() {
        try {
            log.info("===synShenFeiInfo start===");
            Role role = this.userDao.getRoleInfoByName("SystemNormalSearch");
            this.userDao.synAndCloseShenFeiUser();
            List<ShenFeiUserDTO> shenFeiUserDTOS = this.userDao.getShenFeiUserInfo();
            if (CollectionUtils.isNotEmpty(shenFeiUserDTOS)) {
                shenFeiUserDTOS.forEach((shenFeiUserDTO) -> {
                    User userInfo = this.userDao.findByAccount(shenFeiUserDTO.getAvicUserAccount());
                    if (!ObjectUtils.isEmpty(userInfo)) {
                        userInfo.setStatus("Open");
                        userInfo.setUpdateBy("autoAdd");
                        userInfo.setUpdateTime(new Date());
                        userInfo.setUserSecurity(shenFeiUserDTO.getAvicUserSecurity());
                        this.userDao.update(userInfo);
                    } else {
                        User user = new User();
                        user.setEmail(shenFeiUserDTO.getMail());
                        user.setPhoneNumber("13000000000");
                        user.setUserName(shenFeiUserDTO.getAvicUserAccount());
                        user.setTrueName(shenFeiUserDTO.getFullname());
                        user.setCreateBy("autoAdd");
                        user.setCreateTime(new Date());
                        user.setPassword(Sm3Utils.encrypt("AVIC!@#789"));
                        user.setStatus("Open");
                        user.setDeleteFlag(0);
                        user.setIsActive(1);
                        user.setGender("male");
                        user.setUserSecurity(shenFeiUserDTO.getAvicUserSecurity());
                        this.addUser(user, role.getId().toString());
                    }

                });
            }

            List<ShenFeiOrgDTO> shenFeiOrgDTOS = this.userDao.getShenFeiOrgInfo();
            if (CollectionUtils.isEmpty(shenFeiOrgDTOS)) {
                log.info("===getShenFeiOrgInfo is Null ERROR，please check table avic_dept===");
            } else {
                this.userDao.clearShenFeiOrgUserRel();
                this.userDao.clearShenFeiOrgInfo();
                shenFeiOrgDTOS.forEach((shenFeiOrgDTO) -> {
                    UserGroup userGroup = new UserGroup();
                    if (!"0".equals(shenFeiOrgDTO.getAvicDeptCode())) {
                        userGroup.setId(Integer.parseInt(shenFeiOrgDTO.getAvicDeptCode()));
                        int parentId = Integer.parseInt(null != shenFeiOrgDTO.getAvicParentDeptCode() ? shenFeiOrgDTO.getAvicParentDeptCode() : "1");
                        if (0 == parentId) {
                            parentId = 1;
                        }

                        userGroup.setParentId(parentId);
                        userGroup.setDescription(shenFeiOrgDTO.getAvicDeptName());
                        userGroup.setType(UserGroupType.DEPARTMENT.getName());
                        userGroup.setName(shenFeiOrgDTO.getAvicDeptName());
                        userGroup.setEdit(1);
                        userGroup.setDelete(1);
                        this.userGroupDao.addGroupForAvic(userGroup);
                    }
                });
                shenFeiOrgDTOS.forEach((shenFeiOrgDTO) -> {
                    List<UserParam> users = this.userDao.getUserByAvicOrgCode(shenFeiOrgDTO.getAvicDeptCode());
                    if (!CollectionUtils.isEmpty(users)) {
                        List<String> userIds = (List)users.stream().map(UserParam::getUserId).distinct().collect(Collectors.toList());
                        this.userGroupDao.addUsersByGroupId(Integer.parseInt(shenFeiOrgDTO.getAvicDeptCode()), userIds);
                    }
                });
                log.info("===synShenFeiInfo syn end===");
            }
        } catch (Exception var4) {
            log.error("===synShenFeiInfo ERROR===", var4);
            throw var4;
        }
    }

    public void exportDataToWorkbook(String roleId, String status, String userName, String trueName, Integer deptId, String startTime, String endTime, Workbook workbook) {
        new ArrayList();
        new HashMap();
        Date st = null;
        Date et = null;
        long start = System.currentTimeMillis();
        List<UserExport> allUser = this.userDao.findAllUser();
        long end = System.currentTimeMillis();
        log.info("export user: get user cost{}", end - start);
        List<Role> roleList = this.roleService.findRoleList();
        Map<Integer, String> roleMap = (Map)roleList.stream().collect(Collectors.toMap(Role::getId, Role::getRoleName));
        List<UserGroup> allGroup = this.userGroupDao.getAllGroup();
        Map<Integer, String> groupMap = (Map)allGroup.stream().collect(Collectors.toMap(UserGroup::getId, UserGroup::getName));
        String[] tableHeads = new String[]{"序号", "姓名", "用户名", "性别", "电话", "机构", "角色", "密级", "创建时间"};
        Sheet sheet = workbook.createSheet("日志");
        Row headRow = sheet.createRow(0);

        int i;
        for(i = 0; i < tableHeads.length; ++i) {
            headRow.createCell(i).setCellValue(tableHeads[i]);
        }

        if (!org.springframework.util.CollectionUtils.isEmpty(allUser)) {
            i = 1;

            for(int j = 0; i <= allUser.size(); ++i) {
                UserExport userParam = (UserExport)allUser.get(j);
                Row tempRow = sheet.createRow(i);
                tempRow.createCell(0).setCellValue((double)i);
                tempRow.createCell(1).setCellValue(userParam.getTrueName());
                tempRow.createCell(2).setCellValue(userParam.getUserName());
                tempRow.createCell(3).setCellValue(userParam.getGender());
                tempRow.createCell(4).setCellValue(userParam.getPhoneNumber());
                tempRow.createCell(5).setCellValue((String)groupMap.get(userParam.getGroupId()));
                List<String> roleName = new ArrayList();
                if (null != userParam.getRoleIds()) {
                    Iterator var30 = userParam.getRoleIds().iterator();

                    while(var30.hasNext()) {
                        String id = (String)var30.next();
                        roleName.add(roleMap.get(Integer.valueOf(id)));
                    }
                }

                tempRow.createCell(6).setCellValue(String.join(",", roleName));
                tempRow.createCell(7).setCellValue(userParam.getUserSecurity());
                if (null != userParam.getCreateTime()) {
                    tempRow.createCell(8).setCellValue(CommonUtils.timestampToDateTimeString((int)(userParam.getCreateTime().getTime() / 1000L), (String)null));
                }

                ++j;
            }
        }

        long exportTime = System.currentTimeMillis();
        log.info("export user: export user cost{}", exportTime - end);
        workbook.setSheetName(0, "用户清单");
    }

    public void downWorkBookToPC(HttpServletResponse response, Workbook workbook, String fileName) throws IOException {
        response.setHeader("content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
        response.setContentType("application/ynd.ms-excel;charset=UTF-8");
        OutputStream stream = response.getOutputStream();
        workbook.write(stream);
        stream.flush();
        stream.close();
    }
}